/**
 * BrandBigData.com Inc.
 * Copyright (c) 2016 All Rights Reserved.
 */
package com.qibao.toolkit.util;

import java.math.BigDecimal;

/**
 * @author tracy
 * @version $Id:ArithUtils.java, v0.1 2017/7/31 13:35 tracy
 */
public class ArithUtils {

    private static final int DEF_DIV_SCALE = 10;

    private ArithUtils() {
    }

    /**
     * 加
     *
     * @param d1
     * @param d2
     * @return
     */
    public static BigDecimal add(double d1, double d2) {
        BigDecimal b1 = new BigDecimal(d1);
        BigDecimal b2 = new BigDecimal(d2);
        return b1.add(b2);
    }

    /**
     * 减
     *
     * @param d1
     * @param d2
     * @return
     */
    public static double sub(double d1, double d2) {
        BigDecimal b1 = new BigDecimal(Double.valueOf(d1));
        BigDecimal b2 = new BigDecimal(Double.valueOf(d2));
        return b1.subtract(b2).doubleValue();
    }

    /**
     * 乘
     *
     * @param d1
     * @param d2
     * @return
     */
    public static double mul(double d1, double d2) {
        BigDecimal b1 = new BigDecimal(Double.valueOf(d1));
        BigDecimal b2 = new BigDecimal(Double.valueOf(d2));
        return b1.multiply(b2).doubleValue();
    }

    /**
     * 除
     *
     * @param d1
     * @param d2
     * @return
     */
    public static double div(double d1, double d2) {
        return div(d1, d2, DEF_DIV_SCALE);
    }

    /**
     * 除
     *
     * @param d1
     * @param d2
     * @param scale
     * @return
     */
    public static double div(double d1, double d2, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException("The scale must be a positive integer or zero");
        }
        BigDecimal b1 = new BigDecimal(Double.valueOf(d1));
        BigDecimal b2 = new BigDecimal(Double.valueOf(d2));
        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    public static void main(String[] args) {
        System.out.print(div(5, 3));
    }

}
